import { Toolkit } from "./Toolkit";

const { ccclass, property } = cc._decorator;

@ccclass
export default class AudioTool {

    private static _instance: AudioTool = null;
    public static get instance() {
        if (!AudioTool._instance) {
            AudioTool._instance = new AudioTool();
            AudioTool._instance.init();
        }

        return AudioTool._instance;
    }

    init() {

    }

    audioClipsCache: {
        [name: string]: cc.AudioClip
    } = {};
    play(name: string, loop = false, volume = 1.0) {

        let clip = this.audioClipsCache[name];
        if (null != clip) {
            cc.audioEngine.play(clip, loop, volume);
        }
        else {
            cc.loader.loadRes(`sound/${name}`, cc.AudioClip, (err, resource) => {
                if (!err) {
                    this.audioClipsCache[name] = resource;
                    this.play(name);
                }
                else{
                    Toolkit.logFailure(err);
                }
            });
        }
    }


}
